﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;

namespace Cherry.Agile.RpcService.Client
{
    /// <summary>
    /// 远程服务调用，基于http请求的实现(异步请求)
    /// </summary>
    public class HttpRequestProxy : IServiceProxy 
    {
        private HttpWebRequest webRequst;

        SynchronizationContext sysContext;

        public HttpRequestProxy(string serviceUrl)
        {
            sysContext = SynchronizationContext.Current;
            if (string.IsNullOrEmpty(serviceUrl))
            {
                throw new ArgumentNullException("serviceUrl");
            }
            webRequst = (HttpWebRequest)WebRequest.Create(serviceUrl);
            this.Url = serviceUrl;
        }

        /// <summary>
        /// 统一处理接口
        /// </summary>
        /// <param name="requestBuffer">请求数据（含序列化之后的所有请求单元）</param>
        /// <param name="responseCallback">回调函数</param>
        /// <param name="exceptionHandle">通信异常处理</param>
        public void Process(byte[] requestBuffer, Action<byte[]> responseCallback, Action<Exception> exceptionHandle)
        {
            try
            {
                webRequst.Method = "POST";
                webRequst.ContentType = "application/x-www-form-urlencoded";
                webRequst.BeginGetRequestStream
                ((rqResult) =>
                    { //异步写入请求
                        WebRequest request = rqResult.AsyncState as WebRequest;
                        using (Stream requestStream = request.EndGetRequestStream(rqResult))
                        {
                            requestStream.Write(requestBuffer, 0, requestBuffer.Length);
                        }
                        request.BeginGetResponse( //异步获取响应
                            (responseResult) =>
                            {
                                try
                                {
                                    WebResponse response = ((WebRequest)responseResult.AsyncState).EndGetResponse(responseResult);
                                    using (Stream responseStream = response.GetResponseStream())
                                    {
                                        byte[] responseBuffer = new byte[response.ContentLength];
                                        responseStream.Read(responseBuffer, 0, responseBuffer.Length);
                                        SynchronizeThead(responseBuffer, responseCallback);
                                        //responseCallback(responseBuffer);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    SynchronizeThead(ex,exceptionHandle); //异常线程同步
                                }
                            }
                            , request);
                    }
                    , webRequst
                );
            }
            catch (Exception ex)
            {
                exceptionHandle(ex);
            }
        }

        /// <summary>
        /// 处理线程同步
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="cb"></param>
        protected void SynchronizeThead<T>(T obj, Action<T> cb)
        {
            sysContext.Post((state) => cb((T)state), obj);
        }


        public string Url { get; set; }

        public void Dispose()
        {
            this.webRequst = null;
        }
    }
}
